let keyMap = new Map();
keyMap.set("W", "moveForward");
keyMap.set("S", "moveBackward");
keyMap.set("A", "moveLeft");
keyMap.set("D", "moveRight");
keyMap.set("Q", "moveUp");
keyMap.set("E", "moveDown");

class KeyboardRoaming {
    constructor(viewer) {
        this.viewer = viewer;
        this.initAction();
    }
    static getInstance(viewer) {
        if (!KeyboardRoaming.instance) {
            KeyboardRoaming.instance = new KeyboardRoaming(viewer);
        }
        return KeyboardRoaming.instance;
    }
    initAction() {
        this.action = {
            moveForward: false,
            moveBackward: false,
            moveUp: false,
            moveDown: false,
            moveLeft: false,
            moveRight: false,
        };
    }
    start() {
        this.bindEvent();
    }
    stop() {
        this.unbind();
    }
    bindEvent() {
        this.viewer.clock.onTick.addEventListener(this.onEvent, this);
        document.addEventListener("keydown", this.onKeyDown, false);
        document.addEventListener("keyup", this.onKeyUp, false);
    }
    unbind() {
        this.viewer.clock.onTick.removeEventListener(this.onEvent, this);
        document.removeEventListener("keydown", this.onKeyDown, false);
        document.removeEventListener("keyup", this.onKeyUp, false);
    }
    onKeyDown = e => {
        let code = e.keyCode;
        let flag = String.fromCharCode(code);
        let actionName = keyMap.get(flag);
        if (actionName) {
            this.action[actionName] = true;
        }
    };
    onKeyUp = e => {
        this.initAction();
    };
    onEvent = () => {
        var viewer = this.viewer;
        let camera = viewer.scene.camera;
        let cameraHeight = viewer.scene.globe.ellipsoid.cartesianToCartographic(camera.position).height;
        Object.keys(this.action).map(acitonName => {
            if (this.action[acitonName]) {
                console.log(acitonName);
                camera[acitonName](cameraHeight / 100);
            }
        });
    };
}

export default { Keyboard: KeyboardRoaming };
